package com.soonzlab.server;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.authn.oauth.*;


@SuppressWarnings("serial")
public class GoogleDataAuthServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(GoogleDataAuthServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		String CONSUMER_KEY = AuthDataCenter.CONSUMER_KEY;
		String CONSUMER_SECRET = AuthDataCenter.CONSUMER_SECRET;

		GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
		oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
		oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
		oauthParameters.setScope("https://www.google.com/calendar/feeds/ https://www.googleapis.com/auth/userinfo#email");
		oauthParameters.setOAuthCallback("http://godshunfenger.appspot.com/UpgradeToken.jsp");

		GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
		try {
			//1 new request
			oauthHelper.getUnauthorizedRequestToken(oauthParameters);
			String aSecretToken = oauthParameters.getOAuthTokenSecret(); 

			req.getSession().setAttribute("aSecretToken", aSecretToken);
			
			//2 get auth url
			String approvalPageUrl = oauthHelper.createUserAuthorizationUrl(oauthParameters);
			
			
			//System.out.println(approvalPageUrl);
			log.warning("==approvalPageUrl=="+approvalPageUrl);
			//resp.setContentType("text/html");
			//resp.getWriter().println("<script>window.location.href=\"" + approvalPageUrl + "\"</script>");
			//resp.getWriter().println("<a target=\"_blank\" href=\"" + approvalPageUrl + "\">Retrieve an OAuth Token</a>");
			resp.sendRedirect(approvalPageUrl);

			
		} catch (OAuthException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.warning(e.getMessage());
		} 
	 
	 }
	
}
